package io.renren.controller;

import io.renren.config.FileServerConfig;
import io.renren.util.Base64Utils;
import io.renren.util.DfsUtil;
import io.renren.vo.FileServerResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by ThinkPad on 2018/12/4.
 */
public abstract class AbstractController {

    @Autowired
    private FileServerConfig fileServerConfig;

    /**
     * 使用spring hibernate 校验对象，判断集合中的字段是否有值，集合之外的字段不再关注
     * @param needCheckFields
     * @param bindingResult
     * @return
     */
    public List<String> customizeCheckFieldAdapter(List<String> needCheckFields, BindingResult bindingResult){
             return bindingResult.getFieldErrors()
                    .stream()
                    .filter(fielderror->needCheckFields.contains(fielderror.getField()))
                    .map(fieldError -> fieldError.getDefaultMessage())
                    .collect(Collectors.toList());
    }

    /**
     * 使用spring hibernate 校验对象必输项
     * @param bindingResult
     * @return
     */
    public List<String> customizeCheckFieldAdapter(BindingResult bindingResult) {
        return bindingResult.getFieldErrors()
                .stream()
                .map(fieldError -> fieldError.getDefaultMessage())
                .collect(Collectors.toList());
    }

    /**
     * 上传base64编码的字符串照片
     * @param base64ImageStr
     * @param fileName
     * @return
     */
    public String uploadBase64StrImage(String base64ImageStr,String fileName){
        if(StringUtils.isEmpty(base64ImageStr) || base64ImageStr.indexOf("data:image/png;base64,") == -1) {
            return "";
        }else {
            String format_base64ImageStr = base64ImageStr;//Base64Utils.base64Format(base64ImageStr).replace("data:image/png;base64,", "");
            byte[] bytes = Base64Utils.GenerateImageFromBase64(format_base64ImageStr);
            FileServerResponse fileServerResponse = DfsUtil.uploadFileByBinary(fileName, bytes, ContentType.IMAGE_PNG, fileServerConfig.getImageUploadUrl());
            if (fileServerResponse.isSuccess()) {
                return fileServerResponse.getHttpUrl();
            } else {
                return "";
            }
        }
    }
}
